<template>
  <div>
    <nav-bar></nav-bar>
    <h3>自定义编辑栏目</h3>
    <van-divider
      dashed
      :style="{ color: '#87ceeb', borderColor: '#87ceeb', padding: '0 16px' }"
      >已选栏目</van-divider
    >
    <div class="new-category newcategory">
      <p
        @click="handleCategoryClick(index)"
        v-for="(item, index) in newCat"
        :key="index"
      >
        {{ item.title }}
      </p>
    </div>
    <van-divider
      dashed
      :style="{ color: '#ee0a24', borderColor: '#ee0a24', padding: '0 16px' }"
      >隐藏栏目</van-divider
    >
    <div class="new-category delcategory">
      <p
        @click="delCategoryClick(index)"
        v-for="(item, index) in delCat"
        :key="index"
      >
        {{ item.title }}
      </p>
    </div>
    <button @click="$router.push('/')">返回主页</button>
  </div>
</template>

<script>
  import navBar from '@/components/common/Navbar.vue'
  export default {
    data() {
      return {
        newCat: [],
        delCat: [],
      }
    },
    components: {
      navBar,
    },
    methods: {
      async selectCategory() {
        const res = await this.$http.get('/category')
        this.newCat.push(...res.data)
      },
      handleCategoryClick(index) {
        if (this.newCat.length < 3) {
          this.$msg.fail('最少保留两个')
          return
        }
        this.delCat.push(this.newCat[index])
        this.newCat.splice(index, 1)
      },
      delCategoryClick(index) {
        this.newCat.push(this.delCat[index])
        this.delCat.splice(index, 1)
      },
    },
    created() {
      if (localStorage.getItem('newCat') && localStorage.getItem('delCat')) {
        this.newCat = JSON.parse(localStorage.getItem('newCat'))
        this.delCat = JSON.parse(localStorage.getItem('delCat'))
      } else {
        this.selectCategory()
      }
    },
    watch: {
      newCat() {
        localStorage.setItem('newCat', JSON.stringify(this.newCat))
        localStorage.setItem('delCat', JSON.stringify(this.delCat))
      },
    },
  }
</script>

<style lang="stylus" scoped>
  button
    width: 100%
    text-align: center
    font-size: 18px
    background-color: #fb7299
    color: white
    border: none
    height: 40px
    border-radius: 50px
    cursor: pointer

  h3
    text-align: center
    color: #fb7299

  .new-category
    display: flex
    flex-wrap: wrap

    p
      width: 20%
      text-align: center
      margin: 1.389vw 1.944vw
      padding: 1.944vw 0vw
      border-radius: 50%
      cursor: pointer

  .newcategory
    border: 1px solid #87ceeb
    padding: 5.556vw 2.778vw
    border-radius: 10%

    p
      color: #87ceeb
      border: 0.278vw solid #87ceeb

  .delcategory
    border: 1px solid #ee0a24
    padding: 5.556vw 2.778vw
    border-radius: 10%

    p
      color: #ee0a24
      border: 0.278vw solid #ee0a24
</style>